const path = require("path");
const fs = require("fs");
const { AutoComplete } = require("enquirer");
const { _pPlace, getSubApps } = require("./utils");

const argvWrapper = (argArr) =>
  argArr.map((item) => (item.includes("--") ? item : `--${item}`));

const registryAppName = (appName) => (process.env.PROJECT_NAME = appName);

const registryedAppName = (_argv, idx) => _argv.splice(idx, 1);

const registyCustomEnv = (commander, rest) => {
  const conf = path.resolve(
    __dirname,
    `${_pPlace}/${process.env.PROJECT_NAME}/config/env.js`
  );
  if (!fs.existsSync(conf)) {
    return;
  }
  const _config = {
    serve: {
      default: "devServer"
    },
    build: {
      default: "dev"
    }
  };
  const items = ["devServer", "dev", "release", "master"];
  const args = require("minimist")(argvWrapper(rest));
  const val = args["env"] || _config[commander].default;
  if (items.includes(val)) {
    process.env = {
      ...process.env,
      VUE_APP_ENV: val,
      ...require(conf)
    };
  }
};

const runnedStopStrategy = (commander) =>
  commander === "build" && !process.env.npm_config_report;

const ui = async (commander) => {
  const _config = {
    serve: {
      msg: "waiting for start subApp"
    },
    build: {
      msg: "waiting for start subApp"
    }
  };
  const apps = getSubApps();
  if (apps && apps.length === 1) {
    console.log(`${_config[commander].msg} ${apps[0]} ...`);
    registryAppName(apps[0]);
  } else {
    const res = await new AutoComplete({
      name: "subAppName",
      message: `Pick your subApp's name:`,
      limit: 10,
      initial: 1,
      choices: apps
    }).run();
    console.log(`${_config[commander].msg} ${res} ...`);
    registryAppName(res);
  }
};

module.exports = {
  runnedStopStrategy,
  registryAppName,
  registryedAppName,
  registyCustomEnv,
  argvWrapper,
  ui
};
